package com.cskaoyan.controller.admin;

import com.cskaoyan.bean.BaseData;
import com.cskaoyan.bean.bo.StorageParam;
import com.cskaoyan.bean.pojo.MallStorage;
import com.cskaoyan.bean.vo.BaseRespVo;
import com.cskaoyan.service.StorageService;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.mongo.embedded.EmbeddedMongoProperties;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Date;

/**
 * @author: Fengyi
 * @description: 对象存储 list create update delete
 * @time: 2021/7/9 17:44
 */
@RequestMapping("admin/storage")
@RestController
public class StorageController {

    @Autowired
    StorageService storageService;

    /**
     * @Author fengyi
     * @description: 对象分页显示，注意逻辑删除
     * @Date 17:45 2021/7/9
     * url: http://localhost:8083/admin/storage/list
     * ?page=1&limit=20&sort=add_time&order=desc
     */
    @RequestMapping("list")
    @RequiresPermissions("admin:storage:list")
    public BaseRespVo storageList(StorageParam param) {
        BaseData<MallStorage> mallStorage = storageService.queryFiles(param);
        return BaseRespVo.ok(mallStorage);
    }

    /**
     * @Author fengyi
     * @description: update对象，修改name update_time
     * @Date 19:43 2021/7/9
     * url: http://localhost:8083/admin/storage/update
     */
    @RequestMapping("update")
    @RequiresPermissions("admin:storage:update")
    public BaseRespVo updateStorage(@RequestBody MallStorage mallStorage,
                                    BindingResult bindingResult) {

        if(bindingResult.hasFieldErrors()) {
            FieldError fieldError = bindingResult.getFieldError();
            String message = fieldError.getDefaultMessage();
            return BaseRespVo.fail(message);
        }

        Date date = new Date();
        mallStorage.setUpdateTime(date);
        mallStorage.setAddTime(null);

        storageService.updateStorage(mallStorage);

        return BaseRespVo.ok(mallStorage);
    }

    /**
     * @Author fengyi
     * @description: 删除 storage 逻辑删除 deleted
     * @Date 19:56 2021/7/9
     * url:http://localhost:8083/admin/storage/delete
     */
    @RequestMapping("delete")
    @RequiresPermissions("admin:role:delete")
    public BaseRespVo deleteStorage(@RequestBody MallStorage mallStorage) {
        storageService.deleteStorage(mallStorage);
        return BaseRespVo.ok();
    }

}
